<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="modalTitle"
    @ok="onButtonOkClick"
    width="500px"
    :body-style="bodyStyle"
  >
    <BasicForm @register="registerForm" />
    <div>
      <span style="color: darkgray; margin-left: 1rem">
        操作说明：自动按一个班次值班的天数将起止日期范围分为N个班次，每个班次的当班天数均相同。
      </span>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, inject } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';

  import { BatchAddShiftFormSchema } from './dutyschedule.data';
  import { batchSetShift } from '/@/api/duty/dutySchedule';
  import { getByUserDept, getAllDutyGroup } from '/@/api/duty/dutygroup';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { useGlobSetting } from '/@/hooks/setting';

  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'BatchAddShift',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      //获取定义的表单
      const getBatchAddShiftFormSchema = BatchAddShiftFormSchema;

      //弹出窗口界面是新增数据、修改数据；根据传递过来的参数进行判断
      const op = ref(OperationTypeEnum.UN_KNOWN);

      const dataId = ref('');

      const moduleName = inject<string>('moduleName');
      //标题--根据传入的模块名称+操作类型组合得到
      const modalTitle = ref('标题');

      //获取项目编码
      const { globalProjectCode } = useGlobSetting();
      const projectCode = ref<String>(globalProjectCode);

      const bodyStyle = {
        height: '350px',
        // overflow: 'hidden',
        // overflowY: 'scroll',
      };

      const [registerForm, { resetFields, validate, updateSchema }] = useForm({
        labelWidth: 80,
        schemas: getBatchAddShiftFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      /**
       * 根据父组件传递过来的参数获取对应的操作，操作不同所对应的界面不同
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        console.log(data);
        //接收父组件传递的数据
        if (data?.op) {
          //判断是否传入op属性
          op.value = data.op;
        }

        if (data?.dataId) {
          dataId.value = data.dataId;
        }

        if (moduleName) {
          modalTitle.value = unref(moduleName);
        }
        if (op.value != OperationTypeEnum.UN_KNOWN && op.value != OperationTypeEnum.CUSTOME) {
          modalTitle.value += '--' + op.value;
        }

        resetFields(); //重置表单
        setModalProps({ confirmLoading: false });

        if (projectCode.value === 'yzh') {
          getDutyGroupsByUserDept();
        } else {
          getDutyGroups();
        }
      });

      /**
       * 获取当前用户所属部门的值班分组，用于下拉列表显示
       */
      function getDutyGroupsByUserDept() {
        //值班分组选项集合
        let groupOptions = [];
        getByUserDept()
          .then((res) => {
            console.log('res', res);
            res.forEach((group) => {
              //options的value类型必须与表单中对应字段的类型一致，否则无法自动选中
              groupOptions.push({ value: group.id, label: group.name });
            });

            //设置值班分组下拉列表
            updateSchema({
              field: 'groupids',
              componentProps: {
                options: groupOptions,
              },
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            // createMessage.error(ex.msg);
          });
      }

      /**
       * 获取所有值班分组
       */
      function getDutyGroups() {
        //值班分组选项集合
        let groupOptions = [];
        getAllDutyGroup()
          .then((res) => {
            console.log('res', res);
            res.forEach((group) => {
              //options的value类型必须与表单中对应字段的类型一致，否则无法自动选中
              groupOptions.push({ value: group.id, label: group.name });
            });

            //设置值班分组下拉列表
            updateSchema({
              field: 'groupids',
              componentProps: {
                options: groupOptions,
              },
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            // createMessage.error(ex.msg);
          });
      }

      /**
       * 点击确认按钮，保存数据
       */
      async function onButtonOkClick() {
        const values = await validate();
        setModalProps({ confirmLoading: true });
        //调用接口进行保存
        batchSetShift(values)
          .then((res) => {
            if (!res || Object.keys(res).length == 0) {
              createMessage.success('批量设置成功。', 2);
            }
            closeModal();
            emit('success');
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
        setModalProps({ confirmLoading: false });
      }

      return {
        op,
        moduleName,
        modalTitle,
        registerModal,
        registerForm,
        getDutyGroupsByUserDept,
        getDutyGroups,
        onButtonOkClick,
        bodyStyle,
      };
    },
  });
</script>
